<template>
  <div class="article-list">
    <!-- 列表list组件 -->
    <van-pull-refresh
      v-model="isRefreshLoading"
      @refresh="onRefresh"
      :success-text="refreshSuccessText"
    >
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
        :error.sync="error"
        error-text="请求失败，点击重新加载"
      >
        <!-- <van-cell
          v-for="(article, i) in list"
          :key="i"
          :title="article.title"
        /> -->
        <article-item
          v-for="(article, i) in list"
          :key="i"
          :article="article"
        />
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
import { getArticles } from "@/api/article.js";
import ArticleItem from "@/components/article-item.vue";
export default {
  name: "articleList",
  components: {
    "article-item": ArticleItem,
  },
  props: {
    channel: {
      type: Object,
      required: true,
    },
  },
  data() {
    return {
      list: [],
      loading: false,
      finished: false,
      timestamp: Date.now(),
      error: false,
      isRefreshLoading: false,
      refreshSuccessText: "刷新成功",
    };
  },

  methods: {
    async onLoad() {
      try {
        // 1.发送ajax获取文章
        const { data: res } = await getArticles({
          channel_id: this.channel.id,
          timestamp: this.timestamp,
          with_top: 1,
        });
        // console.log(res);
        // 2.文章数据赋值给list
        console.log(res);
        this.list.push(...res.data.results);
        // 3.设置请求loading为false
        this.loading = false;
        // 4.设置请求结束或下一页请求的时间戳
        if (res.data.results.length) {
          this.timestamp = res.data.pre_timestamp;
        } else {
          this.finished = true;
        }
      } catch (err) {
        // console.log(err);
        this.error = true;
        this.loading = false;
      }
    },
    async onRefresh() {
      try {
        // 1.发送ajax获取文章
        const { data: res } = await getArticles({
          channel_id: this.channel.id,
          timestamp: Date.now(),
          with_top: 1,
        });
        // console.log(res);
        // 2.文章数据赋值给list
        console.log(res);
        this.list.unshift(...res.data.results);

        // 3.刷新状态设置为false
        this.isRefreshLoading = false;

        // 4.设置下拉成功的提示文本
        this.refreshSuccessText = `刷新成功${res.data.results.length}条数据`;
      } catch (err) {
        // console.log(err);
        this.refreshSuccessText = "刷新失败";
        isRefreshLoading = false;
      }
    },
  },
  created() {},
};
</script>

<style lang="less" scoped>
// .article-list {
//   position: fixed;
//   top: 180px;
//   bottom: 100px;
//   right: 0;
//   left: 0;
// 	overflow-y: auto;
// }
</style>